import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    user: {},
    userType: null,
    username: null,
    mobile: null,
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_MOBILE: (state, mobile) => {
    state.mobile = mobile
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_USERTYPE: (state, userType) => {
    switch (userType) {
      case 1:
        state.roles = ['teacher']
        break
      case 2:
        state.roles = ['student']
        break
      case 3:
        state.roles = ['admin']
        break
    }
    state.userType = userType
  }
}

const actions = {
  // user login
  login({commit, dispatch}, userInfo) {
    const {username, password, userType} = userInfo
    return new Promise((resolve, reject) => {
      login(username.trim(), password, userType).then(response => {
        const {data} = response
        commit('SET_TOKEN', data)
        setToken(data)
        dispatch('getInfo').then(user => {
          commit('SET_USER', user)
          resolve()
        })
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const {data} = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {username, userType, name, mobile} = data

        commit('SET_NAME', name)
        commit('SET_USERNAME', username)
        commit('SET_MOBILE', mobile)
        commit('SET_USERTYPE', userType)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

